<template>
  <div class="order-management">
    <el-card class="search-box">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="收货人">
          <el-input v-model="searchForm.consignee" placeholder="请输入收货人" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.orderState" placeholder="请选择订单状态" clearable>
            <el-option label="已受理" value="已受理" />
            <el-option label="已完成" value="已完成" />
            <el-option label="派送中" value="派送中" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-box">
      <el-table :data="orderList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNo" label="订单号" width="120" />
        <el-table-column prop="orderTime" label="下单时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.orderTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="consignee" label="收货人" width="100" />
        <el-table-column prop="deliverAddress" label="送货地址" width="150" />
        <el-table-column prop="deliveryTime" label="送达时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.deliveryTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="100" />
        <el-table-column prop="orderAmount" label="订单金额" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.orderAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderState" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.orderState)">{{ row.orderState }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next, sizes, total"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getOrderList, getOrderDetail } from '@/api/account'

// 搜索表单
const searchForm = ref({
  orderNo: '',
  consignee: '',
  phone: '',
  orderState: '',
  dateRange: []
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 订单数据
const orderList = ref([])

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr || dateStr === '0000-00-00 00:00:00') return '-'
  return dateStr.replace('T', ' ').replace('.000Z', '')
}

// 根据状态获取标签类型
const getStatusType = (status) => {
  switch (status) {
    case '已受理': return 'primary'
    case '已完成': return 'success'
    case '派送中': return 'warning'
    default: return 'info'
  }
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      orderNo: searchForm.value.orderNo,
      consignee: searchForm.value.consignee,
      phone: searchForm.value.phone,
      orderState: searchForm.value.orderState,
      date: searchForm.value.dateRange?.length ? JSON.stringify(searchForm.value.dateRange) : undefined
    }

    const res = await getOrderList(params)
    orderList.value = res.data
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    orderNo: '',
    consignee: '',
    phone: '',
    orderState: '',
    dateRange: []
  }
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchOrders()
}

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 查看订单详情
const handleView = async (row) => {
  try {
    const res = await getOrderDetail({ id: row.id })
    console.log('订单详情:', res.data)
    // 这里可以打开详情弹窗或跳转到详情页
    ElMessage.success(`查看订单 ${row.orderNo}`)
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    console.error('获取订单详情失败:', error)
  }
}

// 编辑订单
const handleEdit = (row) => {
  console.log('编辑订单:', row)
  // 这里可以打开编辑弹窗或跳转到编辑页
  ElMessage.success(`编辑订单 ${row.orderNo}`)
}

// 初始化加载数据
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}
.search-box {
  margin-bottom: 20px;
}
.table-box {
  margin-top: 20px;
}
</style>